#include "CameraManager.hpp"
#include "CameraObject.hpp"
#include "../Mouse/MouseManager.hpp"

#include <assert.h>
#include <map>

CameraManager*                CameraManager::m_instance     = 0;

CameraManager* CameraManager::GetInstance()
{
	if( !m_instance )
	{
		m_instance = new CameraManager;
	}

	return m_instance;
}

CameraManager::CameraManager()
{
	m_idIndex = m_activeCamera = 0;
}

void CameraManager::RegisterCamera( CameraObject* newCamera )
{
	// Check if camera exists.
	assert( newCamera );

	// Register camera with unique ID.
	newCamera->SetID( GenerateUniqueID() );
	m_cameras.insert( std::make_pair( newCamera->GetID(), newCamera ) );
}

//! Here all entities are unregistered and destroyed.
void CameraManager::UnregisterAllCameras()
{
	std::map<int, CameraObject*>::iterator mapBegin = m_cameras.begin();
	std::map<int, CameraObject*>::iterator mapEnd   = m_cameras.end();

	for( mapBegin; mapBegin != mapEnd; ++mapBegin )
	{
		m_camerasToDestroy.push_back( mapBegin->first );
	}



	std::vector<int>::iterator beginOfUnregistered = m_camerasToDestroy.begin();
	std::vector<int>::iterator endOfUnregistered   = m_camerasToDestroy.end();

	// Destroy unregistered entities.
	for( beginOfUnregistered; beginOfUnregistered != endOfUnregistered; ++ beginOfUnregistered )
	{
		delete m_cameras[ *beginOfUnregistered ];
		m_cameras[ *beginOfUnregistered ] = NULL;
		//m_entitiesMap.erase( *beginOfUnregistered );
	}
}

//! Unregistered entity will be destroyed on next UpdateScene() call.
void CameraManager::UnregisterCamera(int entityID)
{
	m_camerasToDestroy.push_back( entityID );
}

void CameraManager::SetActiveCamera(int cameraID)
{
	m_activeCamera = cameraID;
	m_cameras[m_activeCamera]->InvalidateView();
}

void CameraManager::Update(clock_t tick)
{
	if( CameraManager::GetInstance()->HaveCameras() )
		m_cameras[m_activeCamera]->Update( tick );

	// Poor testing.
	/*if( CameraManager::GetInstance()->HaveCameras() )
	{
		if( MouseManager::GetInstance()->GetClickCounter() % 2 )
			CameraManager::GetInstance()->SetActiveCamera( 1 );
		else
			CameraManager::GetInstance()->SetActiveCamera( 2 );
	}*/
}

bool CameraManager::HaveCameras()
{
	if( m_cameras.empty() )
		return false;

	return true;
}

CameraObject* CameraManager::GetActiveCamera()
{
	return m_cameras[m_activeCamera];
}